<?php

namespace interface\lzz;

use verify;

require_once 'app.php';

class index
{
    use app;

    protected array $powerAll = [];
    protected array $controlPower = [];
    protected static array $user = [];                //账户信息
    protected static string $stid = '';                //'aefa5c6f4022e2ca';//'Ore126054470Vd';//员工ID
    protected array $control = [];                //员工信息
    protected array $controlJob = [];                //职位
    protected array $controlDepartment = [];                //部门
    protected static string $coid = '';
    public array $resp = [];
    public int $code = 0;
    protected array $timeOption = ['今天', '近7天', '近30天', '自定义'];
    private int $loginState = 0; //登录状态  1为登录
    private static string $keyString = '';
    private array $whiteCla = ['user'];                              //无需登录的类
    private string $loginWarn = ''; //登录提示


    public function __construct()
    {
        $this->init();                    //常用参数
        $cla   = $this->get('cla') ?? '';                    // 类型
        $token = !empty($this->header['Auth']) ? $this->header['Auth'] : '';
        if (!in_array($cla, $this->whiteCla)) {
            //以上三类不需要登录
            $warn = $this->checkToken($token);
            if ($warn !== true) {
                $this->loginState = -1;
                $this->loginWarn  = $warn;
            }
        }
    }

    /**
     * 主函数
     *
     * @return void
     */
    public function main(): void
    {
        $cla = $this->get('cla') ?? '';     // 类型
        $act = $this->get('fun') ?? 'index';// 方法
        if (!$cla) {
            exit('<h2>Error</h2>');
        } else {
            if (!in_array($cla, $this->whiteCla) && in_array($this->loginState, [-1, 0])) {
                $this->resp['warn'] = $this->loginWarn;
                $this->code         = $this->loginState;
                return;
            }
            if (!in_array($cla, ['index', 'app'])) {
                $cla .= str_contains($cla, 'Class') ? '' : 'Class'; // 追加Class 名
            }
            $cla = __NAMESPACE__ . '\\' . $cla;
            $obj = new $cla();
            // 检测是否可以调用
            if (method_exists($obj, $act) && is_callable([$obj, $act])) {
                $obj->$act();
            } else {
                exit('<h2>Modules don\'t exist</h2>');
            }
        }
    }

    /**
     * 查找当前使用的coid
     *
     * @return mixed
     */
    public static function findCoid(): mixed
    {
        $record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
        if (empty($record['id'])) {
            $company = query('company', "isDel = 0");
            self::updateCoidRecord($company['coid']);
            return $company['coid'];
        }
        return $record['value'];
    }

    /**
     * 记录当前使用的账套
     */
    public static function updateCoidRecord($coid): bool
    {
        if (empty($coid)) {
            return false;
        }
        $record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
        if (empty($record['id'])) {
            $warn = static::insert(array(
                'table' => 'user_setting',
                'field' => [
                    'type'  => '当前使用账套',
                    'value' => $coid,
                    'stid'  => self::$stid,
                ],
            ));
        } else {
            $warn = static::update(array(
                'table' => 'user_setting',
                'field' => [
                    'value' => $coid,
                ],
                'where' => "id = '$record[id]'",
            ));
        }
        if (in_array($warn, ['新增成功', '更新成功'])) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查token是否失效
     */
    public function checkToken($token): bool|string
    {
        if (!$token) {
            return '你未登录，请登录';
        } else {
            $stid = $this->rGet($token);
            if (!$stid) {
                return '登录凭证已过期，请重新登录';
            } else {
                $staff = query('staff', " state !='离职' AND stid = '$stid' ");
                if (!$staff) {
                    return '未找到此用户';
                } else {
                    return true;
                }
            }
        }
    }

    /**
     * 签名校验
     * @param $params
     * @return string|bool
     */
    function checkSign($params): string|bool
    {
        $field      = [
            'sign'      => $this->get('sign'),
            'timestamp' => $this->get('timestamp'),
        ];
        $annotation = [
            'sign'      => '签名参数',
            'timestamp' => '签名参数 timestamp',
        ];
        $rules      = [
            'sign'      => 'required',
            'timestamp' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0]; // 多个规则提示最前面一条
        } else {
            $params['timestamp'] = $field['timestamp'];
            $signStr             = self::sign($params);
            if ($signStr !== $field['sign']) {
                return '签名错误';
            } else {
                return true;
            }
        }
    }

    static function sign(array $params = [])
    {
        $appKey = '40bbc55d144c46e1996d0c7a1c5a5a46';
        // 按照键名对数组升序排序
        ksort($params);
        // 添加 appKey 到数组中
        $params['key'] = $appKey;
        // 生成签名字符串
        $str             = http_build_query($params);
        $sign            = hash_hmac('sha1', $str, $appKey, true);
        self::$keyString = $str;
        return urlencode(base64_encode($sign));
    }

}

(new index())->main();
